package com.example.service.impl;

import com.example.result.ReturnCode;
import com.example.result.ReturnResult;
import com.example.service.IPartVersionService;
import com.example.vo.PartVersionQueryParamVO;
import com.example.vo.PartVersionResultVO;
import com.huawei.innovation.rdm.coresdk.basic.enums.ConditionType;
import com.huawei.innovation.rdm.coresdk.basic.vo.QueryCondition;
import com.huawei.innovation.rdm.coresdk.basic.vo.QueryRequestVo;
import com.huawei.innovation.rdm.coresdk.basic.vo.RDMPageVO;
import com.huawei.innovation.rdm.lwxminibom.delegator.PartDelegator;
import com.huawei.innovation.rdm.lwxminibom.dto.entity.PartViewDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PartVersionService implements IPartVersionService {

    Logger logger = LoggerFactory.getLogger(PartVersionService.class);

    @Autowired
    PartDelegator partDelegator;

    @Override
    public ReturnResult query(PartVersionQueryParamVO partVersionQueryParamVO) {
        String partId = partVersionQueryParamVO.getPartId();
        long part_id=Long.parseLong(partId);
        logger.info("PartVersionService.query" + "   " + "partId:" + part_id);

        QueryRequestVo queryRequestVo = new QueryRequestVo();
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setJoiner("or");
        queryCondition.addCondition("master.id", ConditionType.EQUAL, part_id);
        queryRequestVo.setFilter(queryCondition);

        List<PartViewDTO> query = partDelegator.find(queryRequestVo, new RDMPageVO());

        if (query == null || query.isEmpty()) {
            return new ReturnResult(ReturnCode.GET_ERR, "查询part的历史版本为空", null);
        }

        List<PartVersionResultVO> result = new ArrayList<>();
        for (PartViewDTO partViewDTO : query) {
            result.add(PartVersionResultVO.builder()
                    .partId(partViewDTO.getMaster().getId().toString())
                    .partNumber(partViewDTO.getMaster().getNumber())
                    .versionId(partViewDTO.getId().toString())
                    .version(partViewDTO.getVersion()+"."+partViewDTO.getIteration())
                    .name(partViewDTO.getName())
                    .build());
        }

        return new ReturnResult(ReturnCode.GET_OK,"查询id为"+part_id+"的part的历史版本成功",result);
    }

    @Override
    public ReturnResult delete(PartVersionQueryParamVO partVersionQueryParamVO) {
        return null;
    }
}
